package com.test.service.Impl;

import com.test.dao.BookMapper;
import com.test.dao.UserMapper;
import com.test.entity.Book;
import com.test.entity.Borrow;
import com.test.entity.BorrowDetails;
import com.test.service.BookService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class BookServiceImpl implements BookService {
    @Resource
    BookMapper bookMapper;
    @Resource
    UserMapper userMapper;

    @Override
    public List<Book> allBook() {
       return bookMapper.allBook();
    }

    @Override
    public void deleteBook(int id) {
        bookMapper.deleteBook(id);
    }

    @Override
    public void insertBook(Book book) {
        bookMapper.insertBook(book);
    }

    @Override
    public void borrowBook(int bid,int uid) {
      Integer sidByUserId=userMapper.getSidByUserId(uid);
      if(sidByUserId==null)
          return ;
      bookMapper.insertBorrow(bid,sidByUserId);
    }

    @Override
    public List<Borrow> getAllBorrow() {
        return bookMapper.getAllBorrow();
    }
    public List<Book> getAllBookWithOutBorrow(){
        //拿到所有Borrow里面的bid;
        //所有书里有的过滤掉
        List<Book> books=bookMapper.allBook();
        List<Integer> borrows=bookMapper.getAllBorrow().stream().map(
                borrow->borrow.getBid()).collect(Collectors.toList());
        return books.stream().filter(book->!borrows.contains(book.getBid())).collect(Collectors.toList());
    }

    @Override
    public List<Book> getAllBorrowBookById(int id) {
        Integer sidByUserId=userMapper.getSidByUserId(id);
        if(sidByUserId==null)
            return Collections.emptyList();
        return bookMapper.getAllBorrowBySid(sidByUserId).stream().map(borrow ->bookMapper.selectByBid(borrow.getBid())).collect(Collectors.toList());
    }

    @Override
    public void returnBook(int bid,int id) {
        Integer sidByUserId=userMapper.getSidByUserId(id);
        if(sidByUserId==null)
            return ;
        bookMapper.deleteBorrowById(bid,sidByUserId);
    }

    @Override
    public List<BorrowDetails> getAllBorrowOnAdmin() {
        return bookMapper.borrowDetailsList();
    }
}
